# @Time : 2024-11-11 17:13
# @Author : Fioman 
# @Phone : 13149920693
"""
解析eap的响应的内容
"""
import json

from eap_control.eap_config import EapConfig
from eap_control.eap_logger import EapLogger
from personal_tool.data_result import DataResult
from web_tool.send_to_web_handler import update_eap_data_model_in_web
from web_tool.tool_data_model import EapDataType

ec = EapConfig()
eapLog = EapLogger()


def parse_response_text_normal(resData):
    """
    解析普通的不带response_body的消息,只有response_head的消息.
    如果消息格式错误,就返回response format error
    :param resData:
    :return:
    """
    if isinstance(resData, dict) and "success" in resData and "error" in resData:
        success = resData["success"]
        error = resData["error"]
        message = error.get("message", "")
        details = error.get("details", "")
        return success, message, details, resData.get("result", {})
    return False, "", "", {}


def parse_file_path_and_parameter_request_response(method, response) -> DataResult:
    """
    解析收到的 FilePathAndParameterRequest 的response,最原始的response内容
    :param method:请求的API方法名称
    :param response:请求的方法对应的响应
    :return:
    """
    dataResult = DataResult()
    success, message, details, result = False, "", "", {}
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {method},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {method},Response:{response},"
                                       f"状态码错误: {responseCode}")
                success, message, details, result = False, responseCode, f"status_code Error: {responseCode}", {}
                dataResult.info = responseCode
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    success, message, details, result = parse_response_text_normal(jsonDict)
                    dataResult.state = True if success else False
                    dataResult.info = message
                    eapLog.print_and_debug(f"Send: {method},responseText:{jsonDict},result:{result}")
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {method},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    success, message, details, result = False, str(jsonError), "", {}
                    dataResult.info = str(jsonError)
    except Exception as e:
        print(f"in parse_device_heartbeat_response() error: {str(e)}")
        success, message, details, result = False, str(e), "", {}
        dataResult.info = str(e)
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [success, message, details, result])
        return dataResult


def parse_user_login_logout_report_response(methodName: str, response, user_no: str, work_type: str) -> DataResult:
    """
    解析收到的 UserLoginLogoutReport 的response,最原始的response内容
    :param method:请求的API方法名称
    :param response:请求的方法对应的响应
    :param user_no:操作员工号
    :param work_type:操作类型
    :return:
    """
    dataResult = DataResult()
    success, message, details, result = False, "", "", {}
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {methodName},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {methodName},Response:{response},"
                                       f"状态码错误: {responseCode}")
                success, message, details, result = False, responseCode, f"status_code Error: {responseCode}", {}
                dataResult.info = responseCode
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    if isinstance(jsonDict, dict) and "success" in jsonDict:
                        dataResult.state = True if jsonDict["success"] else False
                        dataResult.info = f"返回的success: {jsonDict['success']}"
                        eapLog.print_and_debug(f"Send: {methodName},responseText:{jsonDict},result:{result}")
                        if dataResult.state:
                            if work_type == "2":# 如果是登出,就将当前的用户设置为空字符串
                                ec.user_no = ""
                            else:
                                ec.save_eap_params_from_web({"user_no": user_no})
                    else:
                        dataResult.state = False
                        dataResult.info = f"返回的success: {jsonDict['success']}"
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {methodName},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    success, message, details, result = False, str(jsonError), "", {}
                    dataResult.info = str(jsonError)
    except Exception as e:
        print(f"in parse_device_heartbeat_response() error: {str(e)}")
        success, message, details, result = False, str(e), "", {}
        dataResult.info = str(e)
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [success, message, details, result])
        return dataResult


def parse_trace_data_request_response(method, response) -> DataResult:
    """
    解析收到的 TraceDataRequest 的response,最原始的response内容
    :param method:请求的API方法名称
    :param response:请求的方法对应的响应
    :return:
    """
    dataResult = DataResult()
    success, message, details, result = False, "", "", {}
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {method},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {method},Response:{response},"
                                       f"状态码错误: {responseCode}")
                success, message, details, result = False, responseCode, f"status_code Error: {responseCode}", {}
                dataResult.info = responseCode
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    success, message, details, result = parse_response_text_normal(jsonDict)
                    dataResult.state = True if success else False
                    dataResult.info = message
                    eapLog.print_and_debug(f"Send: {method},responseText:{jsonDict},result:{result}")
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {method},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    success, message, details, result = False, str(jsonError), "", {}
                    dataResult.info = str(jsonError)
    except Exception as e:
        print(f"in parse_device_heartbeat_response() error: {str(e)}")
        success, message, details, result = False, str(e), "", {}
        dataResult.info = str(e)
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [success, message, details, result])
        return dataResult


def parse_process_data_report_response(method, response) -> DataResult:
    """
    解析收到的 ProcessDataReport 的response,最原始的response内容
    :param method:请求的API方法名称
    :param response:请求的方法对应的响应
    :return:
    """
    dataResult = DataResult()
    success, message, details, result = False, "", "", {}
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {method},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {method},Response:{response},"
                                       f"状态码错误: {responseCode}")
                success, message, details, result = False, responseCode, f"status_code Error: {responseCode}", {}
                dataResult.info = responseCode
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    success, message, details, result = parse_response_text_normal(jsonDict)
                    dataResult.state = True if success else False
                    dataResult.info = message
                    eapLog.print_and_debug(f"Send: {method},responseText:{jsonDict},result:{result}")
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {method},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    success, message, details, result = False, str(jsonError), "", {}
                    dataResult.info = str(jsonError)
    except Exception as e:
        print(f"in parse_device_heartbeat_response() error: {str(e)}")
        success, message, details, result = False, str(e), "", {}
        dataResult.info = str(e)
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [success, message, details, result])
        return dataResult


def parse_alarm_warning_data_report_response(method, response) -> DataResult:
    """
    解析收到的 AlarmWarningDataReport 的response,最原始的response内容
    :param method:请求的API方法名称
    :param response:请求的方法对应的响应
    :return:
    """
    dataResult = DataResult()
    success, message, details, result = False, "", "", {}
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {method},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {method},Response:{response},"
                                       f"状态码错误: {responseCode}")
                success, message, details, result = False, responseCode, f"status_code Error: {responseCode}", {}
                dataResult.info = responseCode
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    success, message, details, result = parse_response_text_normal(jsonDict)
                    dataResult.state = True if success else False
                    dataResult.info = message
                    eapLog.print_and_debug(f"Send: {method},responseText:{jsonDict},result:{result}")
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {method},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    success, message, details, result = False, str(jsonError), "", {}
                    dataResult.info = str(jsonError)
    except Exception as e:
        print(f"in parse_device_heartbeat_response() error: {str(e)}")
        success, message, details, result = False, str(e), "", {}
        dataResult.info = str(e)
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [success, message, details, result])
        return dataResult


def parse_equipment_status_response(method, response) -> DataResult:
    """
    解析收到的 EquipmentStatus 的response,最原始的response内容
    :param method:请求的API方法名称
    :param response:请求的方法对应的响应
    :return:
    """
    dataResult = DataResult()
    success, message, details, result = False, "", "", {}
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {method},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {method},Response:{response},"
                                       f"状态码错误: {responseCode}")
                success, message, details, result = False, responseCode, f"status_code Error: {responseCode}", {}
                dataResult.info = responseCode
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    success, message, details, result = parse_response_text_normal(jsonDict)
                    dataResult.state = True if success else False
                    dataResult.info = message
                    eapLog.print_and_debug(f"Send: {method},responseText:{jsonDict},result:{result}")
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {method},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    success, message, details, result = False, str(jsonError), "", {}
                    dataResult.info = str(jsonError)
    except Exception as e:
        print(f"in parse_device_heartbeat_response() error: {str(e)}")
        success, message, details, result = False, str(e), "", {}
        dataResult.info = str(e)
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [success, message, details, result])
        return dataResult


def parse_equipment_total_count_response(method, response) -> DataResult:
    """
    解析收到的 EquipmentTotalCount 的response,最原始的response内容
    :param method:请求的API方法名称
    :param response:请求的方法对应的响应
    :return:
    """
    dataResult = DataResult()
    success, message, details, result = False, "", "", {}
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {method},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {method},Response:{response},"
                                       f"状态码错误: {responseCode}")
                success, message, details, result = False, responseCode, f"status_code Error: {responseCode}", {}
                dataResult.info = responseCode
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    success, message, details, result = parse_response_text_normal(jsonDict)
                    dataResult.state = True if success else False
                    dataResult.info = message
                    eapLog.print_and_debug(f"Send: {method},responseText:{jsonDict},result:{result}")
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {method},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    success, message, details, result = False, str(jsonError), "", {}
                    dataResult.info = str(jsonError)
    except Exception as e:
        print(f"in parse_device_heartbeat_response() error: {str(e)}")
        success, message, details, result = False, str(e), "", {}
        dataResult.info = str(e)
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [success, message, details, result])
        return dataResult


def parse_equipment_information_response(method, response) -> DataResult:
    """
    解析收到的 EquipmentCurrentDateTime 的response,最原始的response内容
    :param method:请求的API方法名称
    :param response:请求的方法对应的响应
    :return:
    """
    dataResult = DataResult()
    success, message, details, result = False, "", "", {}
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {method},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {method},Response:{response},"
                                       f"状态码错误: {responseCode}")
                success, message, details, result = False, responseCode, f"status_code Error: {responseCode}", {}
                dataResult.info = responseCode
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    success, message, details, result = parse_response_text_normal(jsonDict)
                    dataResult.state = True if success else False
                    dataResult.info = message
                    eapLog.print_and_debug(f"Send: {method},responseText:{jsonDict},result:{result}")
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {method},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    success, message, details, result = False, str(jsonError), "", {}
                    dataResult.info = str(jsonError)
    except Exception as e:
        print(f"in parse_device_heartbeat_response() error: {str(e)}")
        success, message, details, result = False, str(e), "", {}
        dataResult.info = str(e)
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [success, message, details, result])
        return dataResult


def parse_equipment_current_date_time_response(response) -> DataResult:
    """
    解析收到的 EquipmentCurrentDateTime 的response,最原始的response内容
    :param method:请求的API方法名称
    :param response:请求的方法对应的响应
    :return:
    """
    method = "EquipmentCurrentDateTime"
    dataResult = DataResult()
    success, message, details, result = False, "", "", {}
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {method},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {method},Response:{response},"
                                       f"状态码错误: {responseCode}")
                success, message, details, result = False, responseCode, f"status_code Error: {responseCode}", {}
                dataResult.info = responseCode
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    success, message, details, result = parse_response_text_normal(jsonDict)
                    dataResult.state = True if success else False
                    dataResult.info = message
                    eapLog.print_and_debug(f"Send: {method},responseText:{jsonDict},result:{result}")
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {method},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    success, message, details, result = False, str(jsonError), "", {}
                    dataResult.info = str(jsonError)
    except Exception as e:
        print(f"in parse_device_heartbeat_response() error: {str(e)}")
        success, message, details, result = False, str(e), "", {}
        dataResult.info = str(e)
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [success, message, details, result])
        return dataResult


def parse_are_you_there_response(method, response) -> DataResult:
    """
    解析收到的 AreYouThereRequest 的response,最原始的response内容
    :param method:请求的API方法名称
    :param response:请求的方法对应的响应
    :return:
    """
    dataResult = DataResult()
    success, message, details, result = False, "", "", {}
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {method},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {method},Response:{response},"
                                       f"状态码错误: {responseCode}")
                success, message, details, result = False, responseCode, f"status_code Error: {responseCode}", {}
                dataResult.info = responseCode
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    success, message, details, result = parse_response_text_normal(jsonDict)
                    dataResult.state = True if success else False
                    dataResult.info = message
                    eapLog.print_and_debug(f"Send: {method},responseText:{jsonDict},result:{result}")
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {method},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    success, message, details, result = False, str(jsonError), "", {}
                    dataResult.info = str(jsonError)
    except Exception as e:
        print(f"in parse_device_heartbeat_response() error: {str(e)}")
        success, message, details, result = False, str(e), "", {}
        dataResult.info = str(e)
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [success, message, details, result])
        return dataResult


def parse_device_alarm_response(method, response) -> DataResult:
    """
    解析发送报警消息的响应内容
    :param method:
    :param response:
    :return:
    """
    dataResult = DataResult()
    result, rtnCode, rtnMsg = "无响应", "", ""
    jsonDict = {}
    try:
        if response == ec.TimeOut:
            eapLog.print_and_debug(f"Send: {method},Response:{response},超时错误")
            result = response
            dataResult.info = response
        else:
            responseCode = response.status_code
            # 先检查状态码，只有在200时才尝试解析JSON
            if responseCode != 200:
                eapLog.print_and_debug(f"Send: {method},Response:{response},"
                                       f"状态码错误: {responseCode}")
                result, rtnCode, rtnMsg = f"status_code Error: {responseCode}", "", ""
                dataResult.info = result
            else:
                # 状态码为200时，尝试解析JSON
                try:
                    responseText = response.text
                    jsonDict = json.loads(responseText)
                    result, rtnCode, rtnMsg = parse_response_text_normal(jsonDict)
                    dataResult.state = True if result == "OK" else False
                    dataResult.info = result
                    eapLog.print_and_debug(f"Send: {method},responseText:{jsonDict},result:{result}")
                except json.JSONDecodeError as jsonError:
                    # JSON解析失败时的处理
                    eapLog.print_and_debug(f"Send: {method},JSON解析失败: {str(jsonError)}, responseText: {response.text}")
                    result, rtnCode, rtnMsg = f"JSON解析错误: {str(jsonError)}", "", ""
                    dataResult.info = result
    except Exception as e:
        print(f"in parse_device_alarm_response() error: {str(e)}")
        result, rtnCode, rtnMsg = str(e), "", ""
        dataResult.info = result
    finally:
        update_eap_data_model_in_web(EapDataType.dataJsonReceive, jsonDict)
        update_eap_data_model_in_web(EapDataType.dataParseResult, [dataResult.state,
                                                                   dataResult.info, dataResult.info, result])
        return dataResult
